package com.leyou.gateway.filters;

import com.leyou.auth.constants.JwtConstants;
import com.leyou.auth.dto.Payload;
import com.leyou.auth.dto.UserDetails;
import com.leyou.auth.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpCookie;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author 虎哥
 */
@Slf4j
@Component
public class JwtRefreshFilter implements GlobalFilter, Ordered {

    private final JwtUtils jwtUtils;

    public JwtRefreshFilter(JwtUtils jwtUtils) {
        this.jwtUtils = jwtUtils;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1.获取cookie中的jwt
        HttpCookie httpCookie = exchange.getRequest().getCookies().getFirst(JwtConstants.COOKIE_NAME);
        if (httpCookie == null) {
            // 放行
            return chain.filter(exchange);
        }
        String jwt = httpCookie.getValue();
        try {
            // 2.解析jwt，得到用户信息
            Payload payload = jwtUtils.parseJwt(jwt);
            UserDetails userDetail = payload.getUserDetail();
            // 3.解析完成，刷新jwt
            jwtUtils.refreshJwt(userDetail.getId());
            log.info("用户{}正在访问{}", userDetail.getUsername(), exchange.getRequest().getURI().getPath());
        } catch (Exception e) {
            log.debug("解析用户失败，用户未登录");
        }
        // 4.放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return Ordered.LOWEST_PRECEDENCE;
    }
}
